package com.shanzhi.connection.common;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.IOException;
import java.util.Map;


public class OkHttpClientUtils {

    private static final OkHttpClient client = new OkHttpClient().newBuilder().build();
    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

    public static String postJson(String baseUrl, String route, JSONObject data, Map<String, String> headers) throws IOException {
        String url = baseUrl + route;
        RequestBody body = RequestBody.create(JSON, data.toString());

        Request.Builder builder = new Request.Builder()
                .url(url)
                .header("Content-Type", "application/json")
                .post(body);

        MapUtils.setHeaders(headers, builder, (key, value, b) -> b.header(key, value));
        Response response = client.newCall(builder.build()).execute();


        if (!response.isSuccessful()) {
            throw new IOException("HTTP request failed, status code: " + response.code() + ", response: " + response.body());
        }

        assert response.body() != null;
        return response.body().string();
    }
}
